/*
* License:  This  program  is  free  software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the  Free Software Foundation; either version 3 of the License, or (at your
* option)  any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/

package pcgen.CharacterViewer.fragments;

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import pcgen.CharacterViewer.R;
import pcgen.CharacterViewer.resources.GameResourceAttributeAbility;

public abstract class DamageHealDialogFragment extends CharacterTabContentDialogFragment 
{
	public static DamageHealDialogFragment newInstance(CharacterTabContentFragment fragment, Types type) 
    {
		DamageHealDialogFragment dialog = null;
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    	if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB)
    		dialog = new DamageHealDialogFragmentDefault();
    	else
    		dialog = new DamageHealDialogFragmentPrevious();

        // Pass args to dialog fragment...
        Bundle args = new Bundle();
        args.putString("type", type.toString());
        dialog.setArguments(args);
        
        initFragment(dialog, fragment);
	    
	    return dialog;
    }
	
	public boolean doDialogNegativeClick()
	{
		return getTargetFragmentEx().dialogCancelDamageHeal();
	}
	
	public boolean doDialogPositiveClick()
	{
		int value = getValue();
		boolean special = false;
		if (getCharacter().getFolder().getSettingsDamageHealingSpecial())
			special = _checkBoxSpecial.isChecked();
		
		if (isHeal())
		{
			if (value > _max)
			{
				Toast.makeText(getActivity(), String.format(getString(R.string.dialog_validation_number_above_max), value, _max), Toast.LENGTH_SHORT).show();
				return false;
			}
			
			if (isHealth())
			{
				if (_selectedValue == SELECTED_VALUE_DAMAGE_PRIMARY)
					getCharacter().modifyDamagePrimaryCurrentHealing(value, special);
				else if (_selectedValue == SELECTED_VALUE_DAMAGE_SECONDARY)
					getCharacter().modifyDamageSecondaryCurrentHealing(value, special);
			}
			else if (isAbility())
			{
				GameResourceAttributeAbility ability = getCharacter().getAbilityById(_selectedValue);
				if (ability != null)
					ability.modifyValueHealing(value);
			}
		}
		else if (isDamage())
		{
//			int temp = (_current - value);
//			if (temp < _min)
//			{
//				Toast.makeText(getActivity(), String.format(getString(R.string.dialog_validation_number_below_min), temp, _min), Toast.LENGTH_SHORT).show();
//				return false;
//			}

			if (isHealth())
			{
				if (_selectedValue == SELECTED_VALUE_DAMAGE_PRIMARY)
					getCharacter().modifyDamagePrimaryCurrentDamage(value);
				else if (_selectedValue == SELECTED_VALUE_DAMAGE_SECONDARY)
					getCharacter().modifyDamageSecondaryCurrentDamage(value);
			}
			else if (isAbility())
			{
				GameResourceAttributeAbility ability = getCharacter().getAbilityById(_selectedValue);
				if (ability != null)
					ability.modifyValueDamage(value);
			}
		}

		return getTargetFragmentEx().dialogCompleteDamageHeal();
	}
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        // Get args...
        _type = Types.valueOf(getArguments().getString("type"));
        _title = (isDamage() ? R.string.dialog_damage_heal_title_damage : R.string.dialog_damage_heal_title_heal);

        // Pick a style based on the num.
//	        int style = DialogFragment.STYLE_NORMAL, theme = 0;
//	        switch ((_num-1)%6) 
//	        {
//	            case 1: style = DialogFragment.STYLE_NO_TITLE; break;
//	            case 2: style = DialogFragment.STYLE_NO_FRAME; break;
//	            case 3: style = DialogFragment.STYLE_NO_INPUT; break;
//	            case 4: style = DialogFragment.STYLE_NORMAL; break;
//	            case 5: style = DialogFragment.STYLE_NORMAL; break;
//	            case 6: style = DialogFragment.STYLE_NO_TITLE; break;
//	            case 7: style = DialogFragment.STYLE_NO_FRAME; break;
//	            case 8: style = DialogFragment.STYLE_NORMAL; break;
//	        }
//	        switch ((_num-1)%6) {
//	            case 4: theme = android.R.style.Theme_Holo; break;
//	            case 5: theme = android.R.style.Theme_Holo_Light_Dialog; break;
//	            case 6: theme = android.R.style.Theme_Holo_Light; break;
//	            case 7: theme = android.R.style.Theme_Holo_Light_Panel; break;
//	            case 8: theme = android.R.style.Theme_Holo_Light; break;
//	        }
//	        setStyle(style, theme);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) 
    {
    	final DialogFragment reference = this;
    	
        View view = null;
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    	if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB)
    		view = inflater.inflate(R.layout.dialog_damage_heal, container, false);
    	else
    		view = inflater.inflate(R.layout.dialog_damage_heal_23x, container, false);
        
        getDialog().setTitle(getString(_title));
        
        _layoutInfo = (View)view.findViewById(R.id.layout_info);
        
        _spinnerDamageType = (Spinner)view.findViewById(R.id.list_damage_type);
        
        _checkBoxSpecial = (CheckBox)view.findViewById(R.id.checkbox_special);
    	
        _textCurrent = (TextView)view.findViewById(R.id.text_current);
        _textInputCurrent = (TextView)view.findViewById(R.id.input_current);
        //_textMaxAmount = (TextView)view.findViewById(R.id.text_max_amount);
        //_textInputMaxAmount = (TextView)view.findViewById(R.id.input_max_amount);

        _textCurrent1 = (TextView)view.findViewById(R.id.text_current1);
        _textInfo1 = (TextView)view.findViewById(R.id.text_info1);
        _textInputCurrent1 = (TextView)view.findViewById(R.id.input_current1);
        _textInputMax1 = (TextView)view.findViewById(R.id.input_max1);
        _textInputMin1 = (TextView)view.findViewById(R.id.input_min1);
        _textMax1 = (TextView)view.findViewById(R.id.text_max1);
        _textMin1 = (TextView)view.findViewById(R.id.text_min1);
        
        _textCurrent2 = (TextView)view.findViewById(R.id.text_current2);
        _textInfo2 = (TextView)view.findViewById(R.id.text_info2);
        _textInputCurrent2 = (TextView)view.findViewById(R.id.input_current2);
        _textInputMax2 = (TextView)view.findViewById(R.id.input_max2);
        _textInputMin2 = (TextView)view.findViewById(R.id.input_min2);
        _textMax2 = (TextView)view.findViewById(R.id.text_max2);
        _textMin2 = (TextView)view.findViewById(R.id.text_min2);

        _layoutInfo1 = (View)view.findViewById(R.id.layout_info1);
        _layoutInfo2 = (View)view.findViewById(R.id.layout_info2);
        
        int max = _max - _current;
        int min = Math.abs(_min - _current);
        if (min > max)
        	max = min;
        
        initialize(view);
        setMaxValue(max);
        setMinValue(0);
//	        _picker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() 
//	        {
//				public void onValueChange(NumberPicker picker, int oldVal, int newVal) 
//				{
//					int add = _current + newVal;
//					_textMax.setText(String.valueOf(_max) + "/" + String.valueOf(add));
//					int subtract = _current - newVal;
//					_textMin.setText(String.valueOf(_min) + "/" + String.valueOf(subtract));
//				}
//			});

        _buttonMax = (Button)view.findViewById(R.id.button_max);
        _buttonMax.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
            	setValue(_max);
            }
        });

        _buttonReset = (Button)view.findViewById(R.id.button_reset);
        _buttonReset.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
            	setValue(0);
            }
        });
        
        _buttonOk = (Button)view.findViewById(R.id.button_ok);
        _buttonOk.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
            	if (doDialogPositiveClick())
            		reference.dismiss();
            }
        });
        
        _buttonCancel = (Button)view.findViewById(R.id.button_cancel);
        _buttonCancel.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
            	if (doDialogNegativeClick())
            		reference.dismiss();
            }
        });
        
        setDialogType();
    	enableControls(false);

        return view;
    }
    
    private void setDialogType()
    {
    	String[] tempAbility = new String[] { getString(getGame().getTypeAbilityTitle(0)), getString(getGame().getTypeAbilityTitle(1)), getString(getGame().getTypeAbilityTitle(2)), getString(getGame().getTypeAbilityTitle(3)), getString(getGame().getTypeAbilityTitle(4)), getString(getGame().getTypeAbilityTitle(5)) };
    	String[] tempHealth = new String[] { getString(getGame().getTypeDamagePrimaryTitle()), getString(getGame().getTypeDamageSecondaryTitle()) };
       
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, (isAbility() ? tempAbility : tempHealth));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        _spinnerDamageType.setAdapter(adapter);
        _spinnerDamageType.setOnItemSelectedListener(new OnItemSelectedListener() 
        {
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
			{
				_selectedValue = new Long(id).intValue();
				setupControls(true);
			}

			public void onNothingSelected(AdapterView<?> arg0) 
			{
		    	_selectedValue = -1;
		    	enableControls(false);
			}
		});
    }
    
    private void enableControls(boolean enabled)
    {
        _layoutInfo.setVisibility(View.VISIBLE);
        _buttonCancel.setVisibility(View.VISIBLE);
    	_spinnerDamageType.setVisibility(View.VISIBLE);
    	
    	boolean enabledEdit = enabled;
    	if (enabled && (_max == _min))
    		enabledEdit = false;
    	
    	_buttonMax.setVisibility((enabledEdit ? View.VISIBLE : View.GONE));
    	_buttonOk.setVisibility((enabledEdit ? View.VISIBLE : View.GONE));
    	_buttonReset.setVisibility((enabledEdit ? View.VISIBLE : View.GONE));
    	
    	if (!enabled)
    		_textCurrent.setVisibility((enabled ? View.VISIBLE : View.GONE));
    	if (!enabled)
    		_textInputCurrent.setVisibility((enabled ? View.VISIBLE : View.GONE));
    	//_textMaxAmount.setVisibility((enabled ? View.VISIBLE : View.GONE));
    	//_textInputMaxAmount.setVisibility((enabled ? View.VISIBLE : View.GONE));
    	
    	if (!enabled)
    		_checkBoxSpecial.setVisibility(View.GONE);
    	
    	if (!enabled)
        	_layoutInfo1.setVisibility(View.GONE);
//    	_textMax1.setVisibility((enabled ? View.VISIBLE : View.GONE));
//    	_textInputMax1.setVisibility((enabled ? View.VISIBLE : View.GONE));
//    	_textMin1.setVisibility((enabled ? View.VISIBLE : View.GONE));
//    	_textInputMin1.setVisibility((enabled ? View.VISIBLE : View.GONE));
    	
        if (!enabled)
        	_layoutInfo2.setVisibility(View.GONE);
//    	_textMax2.setVisibility((enabled ? View.VISIBLE : View.GONE));
//    	_textInputMax2.setVisibility((enabled ? View.VISIBLE : View.GONE));
//    	_textMin2.setVisibility((enabled ? View.VISIBLE : View.GONE));
//    	_textInputMin2.setVisibility((enabled ? View.VISIBLE : View.GONE));
    	
    	setVisibility((enabledEdit ? View.VISIBLE : View.GONE));
    }
    
    private boolean isAbility()
    {
    	return ((_type == Types.DamageAbility) || (_type == Types.HealAbility));
    }
    
    private boolean isDamage()
    {
    	return ((_type == Types.DamageHealth) || (_type == Types.DamageAbility));
    }
    
    private boolean isHeal()
    {
    	return !isDamage();
    }
    
    private boolean isHealth()
    {
    	return !isAbility();
    }
    
    private void setupControls(boolean selected)
    {
    	String title = getString(_title);
    	int textCurrent = R.string.blank;
    	int textMax = R.string.blank;
    	//int textMaxAmount = R.string.blank;
    	int textMin = R.string.blank;
		
    	int min = 0;
    	boolean setToCurrent = false;

    	_textCurrent.setVisibility(View.VISIBLE);
    	_textInputCurrent.setVisibility(View.VISIBLE);
    	_textInputCurrent.setText("");
    	
    	_textCurrent1.setVisibility(View.GONE);
    	_textInputCurrent1.setVisibility(View.GONE);
    	_textInputCurrent1.setText("");
    	
    	_textCurrent2.setVisibility(View.GONE);
    	_textInputCurrent2.setVisibility(View.GONE);
    	_textInputCurrent2.setText("");
    	
    	_textInfo1.setText("");
    	_textInfo1.setVisibility(View.GONE);
    	_textInputMax1.setText("");
    	_textInputMin1.setText("");
    	
    	_textInfo2.setText("");
    	_textInfo2.setVisibility(View.GONE);
    	_textInputMax2.setText("");
    	_textInputMin2.setText("");
    	
    	_checkBoxSpecial.setVisibility(View.GONE);

		if (selected)
    	{
    		if (isAbility())
    		{
    			title = getString(isDamage() ? R.string.dialog_damage_heal_title_damage_ability : R.string.dialog_damage_heal_title_heal_ability);

		    	_current = getCharacter().getAbilityById(_selectedValue).getValue();
	    		_min = getCharacter().getAbilityById(_selectedValue).getValueMin();
	    		_max = 0;
	    		if (isHeal())
	    			_max = getCharacter().getAbilityById(_selectedValue).getValueMaxHeal();
	    		else if (isDamage())
	    			_max = getCharacter().getAbilityById(_selectedValue).getValueMaxDamage();
	    			
				this._layoutInfo1.setVisibility(View.VISIBLE);
				this._layoutInfo2.setVisibility(View.GONE);
    	
		    	textCurrent = R.string.dialog_damage_heal_text_current;
				textMax = R.string.dialog_damage_heal_text_max;
				//textMaxAmount = R.string.dialog_damage_heal_text_amount_damage;
				textMin = R.string.dialog_damage_heal_text_min;
				
	    		_textMax1.setText(getString(textMax));
		        _textInputMax1.setText(String.valueOf(_max));
		    	_textMin1.setText(getString(textMin));
		        _textInputMin1.setText(String.valueOf(_min));
			}
			else if (isHealth())
    		{
				textCurrent = R.string.dialog_damage_heal_text_current;
				//textMaxAmount = (isDamage() ? R.string.dialog_damage_heal_text_amount_damage : R.string.dialog_damage_heal_text_amount_heal);
				
				// Primary
				if (_selectedValue == SELECTED_VALUE_DAMAGE_PRIMARY)
	    		{
	    			_current = getCharacter().getDamagePrimaryCurrent();
		    		_max = 0;
		    		_min = getCharacter().getDamagePrimaryMinDamage();
		    		int maxDisplay = 0;
		    		if (isDamage())
		    		{
		    			_max = Math.abs(getCharacter().getDamagePrimaryMaxDamageAdjustment());
		    			maxDisplay = getCharacter().getDamagePrimaryMaxDamage();
		    		}
		    		else if (isHeal())
		    		{
		    			_max = Math.abs(getCharacter().getDamagePrimaryMaxHealAdjustment());
		    			maxDisplay = getCharacter().getDamagePrimaryMaxDamage();
		    		}
		    		
		            title = String.format(getString(R.string.dialog_damage_heal_title_damage2), getString(getGame().getTypeDamagePrimaryTitle()));
	    			if (!isDamage())
	    				title = String.format(getString(R.string.dialog_damage_heal_title_heal2), getString(getGame().getTypeDamagePrimaryTitle()));
	    			
	    			textMax = getGame().getTypeDamagePrimaryTitleMax();
					textMin = getGame().getTypeDamagePrimaryTitleMin();
				
    				if (getCharacter().getFolder().getSettingsDamageTypeHitPoints() || isHeal())
		            {
		            	_layoutInfo1.setVisibility(View.VISIBLE);
						_layoutInfo2.setVisibility(View.GONE);
		    	
				    	_textMax1.setText(getString(getGame().getTypeDamagePrimaryTitleMax()));
				        _textInputMax1.setText(String.valueOf(maxDisplay));
				    	
				    	_textMin1.setText(getString(getGame().getTypeDamagePrimaryTitleMin()));
				        _textInputMin1.setText(String.valueOf(_min));
				        
				        if (getCharacter().getFolder().getSettingsDamageHealingSpecial())
				        {
				        	_checkBoxSpecial.setVisibility(View.VISIBLE);
				        	_checkBoxSpecial.setText(getString(getGame().getTypeHealingDamageSpecialTitle()));
				        }
		            }
		            else if (getCharacter().getFolder().getSettingsDamageTypeVitalityPoints())
		            {
		            	_layoutInfo1.setVisibility(View.VISIBLE);
						_layoutInfo2.setVisibility(View.VISIBLE);
				    	_textInfo1.setVisibility(View.GONE);
				    	_textInfo2.setVisibility(View.GONE);
				    	_textCurrent.setVisibility(View.GONE);
				    	_textInputCurrent.setVisibility(View.GONE);
		    	
				    	_textInfo1.setText(getString(getGame().getTypeDamagePrimaryTitle()) + " = ");
				    	_textInfo1.setVisibility(View.VISIBLE);
				    	
				    	_textMax1.setText(getString(getGame().getTypeDamagePrimaryTitleMax()));
				        _textInputMax1.setText(String.valueOf(maxDisplay));
				    	
				    	_textMin1.setText(getString(getGame().getTypeDamagePrimaryTitleMin()));
				        _textInputMin1.setText(String.valueOf(_min));
		    	
				        _textCurrent1.setVisibility(View.VISIBLE);
				    	_textInputCurrent1.setText(String.valueOf(getCharacter().getDamagePrimaryCurrent()));
				    	_textInputCurrent1.setVisibility(View.VISIBLE);
				        
				        maxDisplay = Math.abs(getCharacter().getDamageSecondaryMax());
				        int minDisplay = getCharacter().getDamageSecondaryMinDamage();
				        
				    	_textInfo2.setText(getString(getGame().getTypeDamageSecondaryTitle()) + " = ");
				    	_textInfo2.setVisibility(View.VISIBLE);
				    	
				    	_textMax2.setText(getString(getGame().getTypeDamagePrimaryTitleMax()));
				        _textInputMax2.setText(String.valueOf(maxDisplay));
				    	
				    	_textMin2.setText(getString(getGame().getTypeDamagePrimaryTitleMin()));
				        _textInputMin2.setText(String.valueOf(minDisplay));
		    	
				        _textCurrent2.setVisibility(View.VISIBLE);
				    	_textInputCurrent2.setText(String.valueOf(getCharacter().getDamageSecondaryCurrent()));
				    	_textInputCurrent2.setVisibility(View.VISIBLE);
		            }
	    		}
	    		// Secondary
	    		else 
	    		{
	    			textMax = getGame().getTypeDamageSecondaryTitleMax();
					textMin = getGame().getTypeDamageSecondaryTitleMin();
				
    				_current = getCharacter().getDamageSecondaryCurrent();
		    		_max = 0;
		    		_min = getCharacter().getDamageSecondaryMinDamage();
		    		int maxDisplay = 0;
		    		if (isDamage())
		    		{
		    			_max = Math.abs(getCharacter().getDamageSecondaryMaxDamageAdjustment());
		    			maxDisplay = getCharacter().getDamageSecondaryMaxDamage();
		    		}
		    		else if (isHeal())
		    		{
		    			_max = Math.abs(getCharacter().getDamageSecondaryMaxHealAdjustment());
		    			maxDisplay = getCharacter().getDamageSecondaryMaxDamage();
		    		}
					
	    			title = String.format(getString(R.string.dialog_damage_heal_title_damage2), getString(getGame().getTypeDamageSecondaryTitle()));
	    			if (!isDamage())
	    				title = String.format(getString(R.string.dialog_damage_heal_title_heal2), getString(getGame().getTypeDamageSecondaryTitle()));
		    		
		    		_layoutInfo1.setVisibility(View.VISIBLE);
					_layoutInfo2.setVisibility(View.GONE);
	    	
			    	_textMax1.setText(getString(textMax));
			        _textInputMax1.setText(String.valueOf(maxDisplay));
			    	_textMin1.setText(getString(textMin));
			        _textInputMin1.setText(String.valueOf(_min));
	    		}
			}
		}	
    	else
    	{
    		_max = 0;
	    	_current = 0;
    	}
    	
		getDialog().setTitle(title);

		_textCurrent.setText(getString(textCurrent));
    	_textInputCurrent.setText(String.valueOf(_current));
        
        setMaxValue(_max);
        setMinValue(min);
        if (setToCurrent)
        	setValue(_current);
        
    	enableControls(selected);
    }
	
	protected abstract void initialize(View view);
	protected abstract int getValue();
	protected abstract void setMaxValue(int value);
	protected abstract void setMinValue(int value);
	protected abstract void setValue(int value);
	protected abstract void setVisibility(int value);
	
	private int _current;
	private int _max;
	private int _min;
	private int _title;
	private Types _type;
	
	private int _selectedValue = -1;
	
	private View _layoutInfo;
	
	private Spinner _spinnerDamageType;
	
	private CheckBox _checkBoxSpecial;
	
	private Button _buttonCancel;
	private Button _buttonMax;
	private Button _buttonOk;
	private Button _buttonReset;
	
	private TextView _textCurrent;
	private TextView _textInputCurrent;
	//private TextView _textMaxAmount;
	//private TextView _textInputMaxAmount;
	private TextView _textCurrent1;
	private TextView _textInfo1;
	private TextView _textInputCurrent1;
	private TextView _textInputMax1;
	private TextView _textInputMin1;
	private TextView _textMax1;
	private TextView _textMin1;
	private TextView _textCurrent2;
	private TextView _textInfo2;
	private TextView _textInputCurrent2;
	private TextView _textInputMax2;
	private TextView _textInputMin2;
	private TextView _textMax2;
	private TextView _textMin2;
	private View _layoutInfo1;
	private View _layoutInfo2;
	
	private static final int SELECTED_VALUE_DAMAGE_PRIMARY = 0;
	private static final int SELECTED_VALUE_DAMAGE_SECONDARY = 1;
	
	public enum Types
	{
		DamageAbility,
		DamageHealth,
		HealAbility,
		HealHealth
	}

	private static final String TAG = DamageHealDialogFragment.class.getSimpleName();
}
